import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "../store";
import axios from "axios";
import { ElMessage } from "element-plus";

export const staticRoutes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () =>
      import(/* webpackChunkName: "home" */ "@/views/home/homeView.vue"),
    meta: {
      breadcrumb: ["首页"],
    },
  },
  {
    path: "/list/add",
    name: "listAdd",
    component: () =>
      import(
        /* webpackChunkName: "listAdd" */ "@/views/listAdd/listAddView.vue"
      ),
    meta: {
      role: "admin",
      breadcrumb: ["列表操作", "列表添加"],
    },
  },
  {
    path: "/list/manage",
    name: "listManage",
    component: () =>
      import(
        /* webpackChunkName: "listManage" */ "@/views/listManage/listManageView.vue"
      ),
    meta: {
      breadcrumb: ["列表操作", "列表管理"],
    },
  },
  {
    path: "/set",
    name: "set",
    component: () =>
      import(/* webpackChunkName: "set" */ "@/views/set/setView.vue"),
    meta: {
      role: "admin",
      breadcrumb: ["设置"],
    },
  },
];

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "mainLayout",
    component: () =>
      import(
        /* webpackChunkName: "mainLayout" */ "@/mainLayout/mainLayoutView.vue"
      ),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/loginView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from) => {
  const token = localStorage.getItem("token");
  const isLogin = store.state.userInfo.isLogin;

  if (token) {
    // token 存在
    if (isLogin) {
      // token 存在 用户已经登录
      if (to.path === "/login") return { name: "home" };
      return true;
    } else {
      // token 存在 用户未登录
      const resp = await axios.get("/api/user/info/" + token);
      const { code, data, message } = resp.data;
      if (code === 200) {
        // 通过
        store.commit("loginSuccess", { ...data, token, isLogin: true });
        return { ...to, replace: true };
      } else {
        // 未通过
        store.commit("loginFail");
        ElMessage({ type: "error", message });
        return { name: "login" };
      }
      return true;
    }
  } else {
    // token 不存在
    if (to.path === "/login") return true;
    return { name: "login" };
  }
});

export default router;
